package com.happy_hao.topbiz.realm;

import com.happy_hao.topbiz.api.UserApi;
import com.happy_hao.topbiz.po.Group;
import com.happy_hao.topbiz.po.Permission;
import com.happy_hao.topbiz.po.User;
import com.happy_hao.topbiz.token.EmailCodeToken;
import com.happy_hao.topbiz.exception.ServiceException;
import com.happy_hao.topbiz.util.RealmUtil;
import com.happy_hao.topbiz.util.RedisUtil;
import jakarta.annotation.Resource;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.data.redis.core.RedisTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class EmailCodeRealm extends AuthorizingRealm {

    @Resource
    private RealmUtil realmUtil;

    @Resource
    private RedisUtil redisUtil;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<Permission> permissions = new HashSet<>(user.getPermissions());
        Set<String> permission = permissions.stream()
                .map(Permission::getPermissionName)
                .collect(Collectors.toSet());

        info.setRoles(permission);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        EmailCodeToken token = (EmailCodeToken) authenticationToken;
        String email = (String) token.getPrincipal();
        User user = realmUtil.getUserByMap(email);
        if (user == null) {
            throw new UnknownAccountException();
        }
        if (!token.getCredentials().equals(redisUtil.get(email))) {
            throw new IncorrectCredentialsException("验证码过期或错误");
        }
        return new SimpleAuthenticationInfo(user, token.getCredentials(), this.getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof EmailCodeToken;
    }
}
